package cn.exrick.common.exception;

import java.net.BindException;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import cn.exrick.pojo.common.Result;
import cn.exrick.utils.ResultUtil;

/**
 * Created by Exrick on 2017/8/20.
 */
@ControllerAdvice
public class RestCtrlExceptionHandler {

    private static Logger log = LoggerFactory.getLogger(RestCtrlExceptionHandler.class);

    @ExceptionHandler(BindException.class)
    @ResponseStatus(value = HttpStatus.OK)
    @ResponseBody
    public Result<Object> bindExceptionHandler(BindException e) {
        String errorMsg = "请求数据校验不合法: ";
        if (e != null) {
            errorMsg = e.getMessage();
            log.warn(errorMsg);
        }
        return new ResultUtil<>().setErrorMsg(errorMsg);
    }

    @ExceptionHandler(XmallException.class)
    @ResponseStatus(value = HttpStatus.OK)
    @ResponseBody
    public Result<Object> handleXmallException(XmallException e) {
        if ("请先登录".equals(e.getMsg())) {
            return new ResultUtil<>().returnNeedLogin();
        }
        String errorMsg = "Xmall exception: ";
        if (e != null) {
            errorMsg = e.getMsg();
            log.warn(e.getMessage());
        }
        return new ResultUtil<>().setErrorMsg(errorMsg);
    }

    @ExceptionHandler(NeedLoginException.class)
    @ResponseStatus(value = HttpStatus.OK)
    @ResponseBody
    public Result<Object> handleNeedLoginException(NeedLoginException e) {
        return new ResultUtil<>().returnNeedLogin();
    }

    @ExceptionHandler(Exception.class)
    @ResponseStatus(value = HttpStatus.OK)
    @ResponseBody
    public Result<Object> handleException(Exception e) {
        String errorMsg = "exception: ";
        if (e != null) {
            e.printStackTrace();
            if (e.getMessage() != null && e.getMessage().contains("Maximum upload size")) {
                errorMsg = "上传文件大小超过3MB限制";
            } else if (e.getMessage() != null && e.getMessage().contains("XmallException")) {
                errorMsg = e.getMessage();
                errorMsg = StringUtils.substringAfter(errorMsg, "XmallException:");
                errorMsg = StringUtils.substringBefore(errorMsg, "\n");
            } else {
                errorMsg = e.getMessage();
            }
        }
        return new ResultUtil<>().setErrorMsg(errorMsg);
    }
}
